package service

import (
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/model/request"
)

//@author: [piexlmax](https://github.com/piexlmax)
//@function: CreateUserIndex
//@description: 创建UserIndex记录
//@param: userIndex model.UserIndex
//@return: err error

func CreateUserIndex(userIndex model.UserIndex) (err error) {
	err = global.GVA_DB.Create(&userIndex).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteUserIndex
//@description: 删除UserIndex记录
//@param: userIndex model.UserIndex
//@return: err error

func DeleteUserIndex(userIndex model.UserIndex) (err error) {
	err = global.GVA_DB.Delete(&userIndex).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteUserIndexByIds
//@description: 批量删除UserIndex记录
//@param: ids request.IdsReq
//@return: err error

func DeleteUserIndexByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]model.UserIndex{},"id in ?",ids.Ids).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: UpdateUserIndex
//@description: 更新UserIndex记录
//@param: userIndex *model.UserIndex
//@return: err error

func UpdateUserIndex(userIndex model.UserIndex) (err error) {
	err = global.GVA_DB.Save(&userIndex).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetUserIndex
//@description: 根据id获取UserIndex记录
//@param: id uint
//@return: err error, userIndex model.UserIndex

func GetUserIndex(id uint) (err error, userIndex model.UserIndex) {
	err = global.GVA_DB.Where("id = ?", id).Preload(`Users`).Preload(`UserIndexIntro`).Preload(`UserIndexTop`).First(&userIndex).Error
	return
}

func GetUserIndexWithUserId(userId int)(err error, userIndex model.UserIndex) {
	err = global.GVA_DB.Where("user_id = ?", userId).Preload(`Users`).Preload(`UserIndexIntro`).Preload(`UserIndexTop`).First(&userIndex).Error
	return
}
//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetUserIndexInfoList
//@description: 分页获取UserIndex记录
//@param: info request.UserIndexSearch
//@return: err error, list interface{}, total int64

func GetUserIndexInfoList(info request.UserIndexSearch,order string) (err error, list interface{}, total int64) {
	global.GVA_DB.Delete(&[]model.UserIndex{},`user_id = 0`)
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&model.UserIndex{})
    var userIndexs []model.UserIndex
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.Status != 0 {
        db = db.Where("`status` = ?",info.Status)
    }
    if info.UserId != 0 {
        db = db.Where("`user_id` = ?",info.UserId)
    }
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Order(order).Preload(`Users`).Preload(`UserIndexIntro`).Preload(`UserIndexTop`).Find(&userIndexs).Error
	return err, userIndexs, total
}